package com.ethen.liveeventbus.slice;

import android.life.livedata.Observer;
import android.log.Log;
import com.ethen.liveeventbus.ResourceTable;
import com.ethen.liveeventbus.event.DemoEvent;
import com.ethen.liveeventbus.service.IpcService;
import com.ohos.liveeventbus.LiveEventBus;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.abilityjet.activedata.DataObserver;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

public class LiveEventAbilitySlice extends AbilitySlice {
    private static final String TAG = "LiveEventAbilitySlice";
    private static final String KEY1 = "event_live";
    private static final String KEY2 = "event_live2";
    private static final String KEY3 = "event_live3";

    public static final String KEY_TEST_OBSERVE = "key_test_observe";
    public static final String KEY_TEST_OBSERVE_FOREVER = "key_test_observe_forever";
    public static final String KEY_TEST_STICKY = "key_test_sticky";
    public static final String KEY_TEST_MULTI_THREAD_POST = "key_test_multi_thread_post";
    public static final String KEY_TEST_MSG_SET_BEFORE_ON_CREATE = "key_test_msg_set_before_on_create";
    public static final String KEY_TEST_CLOSE_ALL_PAGE = "key_test_close_all_page";
    public static final String KEY_TEST_ACTIVE_LEVEL = "key_test_active_level";
    public static final String KEY_TEST_ACTIVE_LEVEL_SINGLE = "key_test_active_level_single";
    public static final String KEY_TEST_BROADCAST = "key_test_broadcast";
    public static final String KEY_TEST_BROADCAST_IN_APP = "key_test_broadcast_in_app";
    public static final String KEY_TEST_BROADCAST_GLOBAL = "key_test_broadcast_global";
    public static final String KEY_TEST_DELAY_LIFE = "key_test_delay_life";

    private Observer<String> foreverOb;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        setUIContent(ResourceTable.Layout_life_request_layout);
        LifeAbilitySlice2 life2 = new LifeAbilitySlice2();

        findComponentById(ResourceTable.Id_btn_life).setClickedListener(component -> {
            LiveEventBus.get(KEY1).post("hi ethen!");
        });

        findComponentById(ResourceTable.Id_btn_life_global).setClickedListener(component -> {
            LiveEventBus.get(KEY1).post(23);
        });

        findComponentById(ResourceTable.Id_btn_life2).setClickedListener(component -> {
            LiveEventBus.get(KEY2).post("hi ethen2222!");
        });

        findComponentById(ResourceTable.Id_btn_to_life2).setClickedListener(component -> {
            present(life2, new Intent());
        });

        findComponentById(ResourceTable.Id_testBroadcastInApp).setClickedListener(component -> testBroadcastInApp());
        findComponentById(ResourceTable.Id_testBroadcastGlobal).setClickedListener(component -> testBroadcastGlobal());
        findComponentById(ResourceTable.Id_sendDemoEvent).setClickedListener(component -> sendDemoEvent());

        initObserve1();
        initObserverForever();
        //因为验证多进程发送LiveEventBus,在MyApplication初始化的时候已经Enable过了。不同进程之间内存空间地址不同，无法进行多进程通讯，所以需要在Application初始化的时候初始化
        // 同一进程内使用则打开该注释，关闭MyApplication中的enable功能，统一进程内存空间地址一样，可以进行通讯
        //不同进程，如本案例中的IpcService，LiveData的空间地址和本类不在一个地址空间内，可参考Linux的多进程通讯知识
        //LiveEventBus.enableAcrossApp();
    }

    @Override
    protected void onActive() {
        super.onActive();
        startAbility(IpcService.class.getName());
    }

    public void sendDemoEvent() {
        LiveEventBus
                .get(DemoEvent.class)
                .post(new DemoEvent("Hello world"));
    }

    public void testBroadcastInApp() {
        LiveEventBus
                .get(KEY_TEST_BROADCAST_IN_APP)
                .postAcrossProcess("broadcast msg");
    }

    public void testBroadcastGlobal() {
        LiveEventBus
                .get(KEY_TEST_BROADCAST_GLOBAL)
                .postAcrossApp("broadcast msg");
    }

    private void initObserve1() {
        LiveEventBus.get(KEY1, String.class).observe(this, s -> {
            new ToastDialog(getContext()).setText(s).setDuration(1000).show();
            Log.d(TAG, "get String.class,key: " + KEY1 + ",value is:" + s);
        });

        LiveEventBus.get(KEY1, Integer.class).observe(this, s -> {
            new ToastDialog(getContext()).setText(String.valueOf(s)).setDuration(1000).show();
            Log.d(TAG, "get Int.class,key: " + KEY1 + ",value is:" + s);
        });

        LiveEventBus.get(DemoEvent.class)
                .observe(this, demoEvent -> {
                    Log.d(TAG,"get event without key:"+ demoEvent.content);
                    showDialog("Receive message: " + demoEvent.content);
                });
    }

    private void initObserverForever() {
        foreverOb = s -> {
            new ToastDialog(getContext()).setText(s).setDuration(1000).show();
            Log.d(TAG, "get Forever String.class,key: " + KEY2 + ",value is:" + s);
        };
        LiveEventBus.get(KEY2, String.class).observeForever(foreverOb);
    }

    public void showDialog(String s) {
        DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_toast_dialog, null, false);
        Text text = layout.findComponentById(ResourceTable.Id_txt_dialog);
        text.setText(s);
        new ToastDialog(this)
                .setContentCustomComponent(layout)
                .setAlignment(LayoutAlignment.CENTER)
                .setDuration(3000)
                .show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopAbility(IpcService.class.getName());
        LiveEventBus.disableAcrossApp();
        LiveEventBus.get(KEY2, String.class).removeObserver(foreverOb);
    }

    private void stopAbility(String abilityNam) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(abilityNam)
                .build();
        intent.setOperation(operation);
        stopAbility(intent);
    }

    private void startAbility(String abilityNam) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(abilityNam)
                .build();
        intent.setOperation(operation);
        startAbility(intent);
    }
}
